﻿


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>介绍 - Promise</title>

    </head>
    <body class="docs"> 
	Promise<br /><br />
<script type="text/javascript">
<!--

function runAsync(){
    var p = new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            console.log('执行完成');
            resolve('随便什么数据');
        }, 2000);
    });
    return p;            
}

runAsync().then(function(data){
	console.log('返回数据');
    console.log(data);
    //后面可以用传过来的数据做些其他操作
    //......
});

function getNumber(){
    var p = new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            var num = Math.ceil(Math.random()*10); //生成1-10的随机数
            if(num<=5){
                resolve(num);
            }
            else{
                reject('数字太大了');
            }
        }, 2000);
    });
    return p;            
}

getNumber()
.then(
    function(data){
        console.log('resolved');
        console.log(data);
    }, 
    function(reason, data){
        console.log('rejected');
        console.log(reason);
    }
);
//-->
</script>
